package com.wantong.jianpu.customviews;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.util.SmartGlideImageLoader;
import com.wantong.jianpu.R;
import com.wantong.jianpu.adapters.SelectImageAdapter;
import com.wantong.jianpu.beans.SelectImageBean;
import com.wantong.jianpu.utils.Constants;
import com.wantong.jianpu.utils.GlideEngine;

import java.util.ArrayList;
import java.util.List;

import me.goldze.mvvmhabit.utils.ToastUtils;

/**
 * @author PACY
 * @date 2022/4/25
 * description:
 */
public class SelectImageView extends LinearLayout {
    private int maxLength;
    private SelectImageAdapter mAdapter;
    private RecyclerView recyclerView;
    private GridLayoutManager layoutManager;
    private List<SelectImageBean> data;
    private FragmentActivity activity;

    private TextView count_tv;

    SelectCallBack callBack;
    public SelectImageView(Context context) {
        super(context);
    }

    public SelectImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        /**
         * 加载布局  获取自定义属性
         */
        LayoutInflater.from(context).inflate(R.layout.select_image_view, this, true);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SelectImageView);
        maxLength = a.getInt(R.styleable.SelectImageView_imageMaxLength,1);
        a.recycle();
    }

    public void setActivity(FragmentActivity activity) {
        this.activity = activity;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        count_tv=findViewById(R.id.count_tv);
        count_tv.setText("0/"+maxLength);
        data=new ArrayList<>();
        data.add(new SelectImageBean(true));
        recyclerView=findViewById(R.id.recyclerView);
        mAdapter=new SelectImageAdapter();
        layoutManager=new GridLayoutManager(getContext(),3);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(mAdapter);
        mAdapter.setNewInstance(data);

        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            if(mAdapter.getItem(position).isAdd()){
                if(mAdapter.getItemCount()-1==maxLength){
                    ToastUtils.show("最多只能添加"+maxLength+"张图片");
                }else{
                    selectPic();
                }

            }else{
                new XPopup.Builder(activity).asImageViewer((ImageView) mAdapter.getViewByPosition(position,R.id.image_iv), mAdapter.getItem(position).getUrl(), new SmartGlideImageLoader()).show();
            }
        });
        mAdapter.addChildClickViewIds(R.id.delete_iv);
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if(view.getId()==R.id.delete_iv){
                mAdapter.removeAt(position);
                if (callBack != null) {
                    callBack.deletePosition(position);
                }
            }
        });
    }

    public void setCallBack(SelectCallBack callBack) {
        this.callBack = callBack;
    }


    public void setData(List<SelectImageBean> data){
        mAdapter.addData(mAdapter.getItemCount()-1,data);
    }
    /**
     * 选择图片
     */
    public void selectPic() {
        //选择图片
        EasyPhotos.createAlbum(activity, true, false, GlideEngine.getInstance())
                .setFileProviderAuthority(Constants.PROVIDER_STRING)
                .setCount(maxLength-(mAdapter.getItemCount()-1))
                .start(new SelectCallback() {
                    @Override
                    public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                        List<String> paths=new ArrayList<>();
                        for (Photo photo : photos) {
                            SelectImageBean imageBean=new SelectImageBean();
                            imageBean.setAdd(false);
                            imageBean.setPath(photo.path);
                            mAdapter.addData(mAdapter.getItemCount()-1,imageBean);
                            paths.add(photo.path);
                        }
                        count_tv.setText(mAdapter.getItemCount()-1+"/"+maxLength);
                        if (callBack != null) {
                            callBack.selectImagePath(paths);
                        }
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    public interface SelectCallBack {
        void selectImagePath(List<String> filePath);

        void deletePosition(int position);
    }
}
